package com.prj.ufdm.auth.security;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSON;
import com.prj.ufdm.auth.enums.AuthRetCodeEnum;
import com.prj.ufdm.core.dto.RetData;
import com.prj.ufdm.core.util.UfdmRequestUtil;

/**
 * TOKEN 验证失败后处理
 * @author 胡义振  
 * @date 2018年3月22日
 */
@Service
public class TokenAuthenticationFailure extends SimpleUrlAuthenticationFailureHandler{
	
	@Override
	public void onAuthenticationFailure(HttpServletRequest request,HttpServletResponse response, AuthenticationException exception)	throws IOException, ServletException {
		//Token 验证异常
		UfdmRequestUtil.addCsrfHeader(response);
		RetData<String> retData = new RetData<>();
		if(AuthRetCodeEnum.RET_CODE_0101005.getCode().equals(exception.getMessage())) {
			retData.getRetHead().setCode(AuthRetCodeEnum.RET_CODE_0101005.getCode());
			retData.getRetHead().setMessage(AuthRetCodeEnum.RET_CODE_0101005.getMessage());
		}
		else if(AuthRetCodeEnum.RET_CODE_0101008.getCode().equals(exception.getMessage())) {
			retData.getRetHead().setCode(AuthRetCodeEnum.RET_CODE_0101008.getCode());
			retData.getRetHead().setMessage(AuthRetCodeEnum.RET_CODE_0101008.getMessage());
		}
		else if(AuthRetCodeEnum.RET_CODE_0101009.getCode().equals(exception.getMessage())) {
			retData.getRetHead().setCode(AuthRetCodeEnum.RET_CODE_0101009.getCode());
			retData.getRetHead().setMessage(AuthRetCodeEnum.RET_CODE_0101009.getMessage());
		}
		else {
		    retData.getRetHead().setCode(AuthRetCodeEnum.RET_CODE_0101006.getCode());
		    retData.getRetHead().setMessage(AuthRetCodeEnum.RET_CODE_0101006.getMessage());
		}
		response.getWriter().write(JSON.toJSONString(retData));
	}
}
